package hyj.qx.kuaican.servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class RouteServlet extends HttpServlet {

    // 获取路由
    private String getRoute(String url) {
        url = url.replaceAll("/Petrescue", "");
        String[] levels = url.split("[?]")[0].split("/");
        return levels[levels.length - 1];
    }

    // 获取当前类的子类
    protected abstract Class getMyClass();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        String url = req.getRequestURI();
        System.out.println("url为：" + url);

        String methodName = getRoute(url);
        Object obj = null;
        try {
            Method method = getMyClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            obj = method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}